<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/8/23
 * Time: 19:43
 */

namespace Biz\module\Classes\mgt;

use Biz\model\activity\ActivityMeal as mActivityMeal;
use Biz\model\activity\ActivityMealInfo as mActivityMealInfo;
use Biz\validate\activity\Meal as vMeal;
use Biz\validate\activity\MealInfo as vMealInfo;
use Biz\model\activity\ActivityOperateLog as mActivityOperateLog;
use Biz\pockets\constInterface\ActivityInfo;

class MealSave extends vMealInfo
{
    public static $goodsId = '';

    public static function update($mealId, $post)
    {
        $mealInfo = array_pop($post);
        $meal = self::checkMealInfo($mealId, $post, $mealInfo);

        $scenes = $mealId > 0 ? 'update' : 'create';

        if (!vMeal::validate($post, $scenes)) {
            $msg = vMeal::firstError();
            throw new \Exception($msg);
        }

        $mealId = mActivityMeal::updateActivityMeal($mealId, $post);
        if(!$mealId) return false;

        if(count($mealInfo) >5) {
            throw new \Exception("每个套餐最多5个分组");
        }

        // 编辑套餐下的商品
        $goodsIds = [];
        foreach ($mealInfo as $key => $value)
        {
            if(count($value) < 1) {
                $key = $key + 1;
                throw new \Exception("分组 $key 内没有商品，请添加商品或者删除该分组");
            } else if(count($value) > 5) {
                throw new \Exception("每个分组最多5个商品");
            }

            foreach ($value as $k => $val)
            {
                if(in_array($val['goods_id'], $goodsIds)) {
                    throw new \Exception("商品重复");
                }

                $goodsIds[] = $val['goods_id'];
                if (!vMealInfo::validate($val, $scenes)) {
                    $msg = vMealInfo::firstError();
                    throw new \Exception($msg);
                }
                vMealInfo::clearRulesList();
                $val['meal_id'] = $mealId;
                $val['group'] = $key;
                $val['shop_id'] = $post['shop_id'];
                $val['is_push'] = $k ? 0 : 1;
                $val['start_time'] = $post['start_time'];
                $val['end_time'] = $post['end_time'];
                $val['addtime'] = date('Y-m-d H:i:s');
                $val['edittime'] = date('Y-m-d H:i:s');
                $mealInfoIds[] = mActivityMealInfo::updateMealInfo($val, isset($meal['status']) ? $meal['status'] : 1);
            }

        }

        // 修改删除的商品的状态
        if(!isset($meal['status']) && !empty($mealInfoIds)) {
            mActivityMealInfo::delNotInMealInfo($mealId, $mealInfoIds);
        }

        array_push($post, $mealInfo);
        $logData = [
            'type_id' => ActivityInfo::ACTIVITY_TYPE_MEAL,
            'activity_id' => $mealId,
            'shop_id' => $post['shop_id'],
            'title' => $post['meal_title'],
            'start_time' => $post['start_time'],
            'end_time' => $post['end_time'],
            'status' => mActivityMeal::STATUS_NORMAL,
            'operate_data' => json_encode($post, JSON_UNESCAPED_UNICODE),
            'operate_type' => 0,
        ];

        $result = mActivityOperateLog::addLogData($logData);

        if($result) {
            return $result;
        } else {
            return false;
        }
    }

    public static function changeStatus($mealId, $status, $meal)
    {
        mActivityMeal::updateStatus($mealId, $status);

        mActivityMealInfo::updateStatus($mealId, $status);

        $logData = [
            'type_id' => ActivityInfo::ACTIVITY_TYPE_MEAL,
            'activity_id' => $mealId,
            'shop_id' => $meal['shop_id'],
            'title' => $meal['meal_title'],
            'start_time' => $meal['start_time'],
            'end_time' => $meal['end_time'],
            'status' => $status,
            'operate_data' => json_encode($meal, JSON_UNESCAPED_UNICODE),
            'operate_type' => 0,
        ];

        $result = mActivityOperateLog::addLogData($logData);

        if($result) {
            return true;
        } else {
            return false;
        }
    }

    public static function setTop($mealId, $isSetTop)
    {
        // 如果为0的话,将sort修改为0,如果为一的话,查询当前表的最大置顶值+1
        if($isSetTop == 0) {
            return mActivityMeal::setTop($mealId);
        } else {
            $maxSort = mActivityMeal::getMaxSort();
            $maxSort ++;
            return mActivityMeal::setTop($mealId, $maxSort);
        }
    }

    public static function checkMealInfo($mealId, &$post, $mealInfo)
    {
        if(count($mealInfo) < 2 || !count($mealInfo)) {
            throw new \Exception('需要至少2组商品才能形成套餐，请添加新分组');
        }

        if($mealId > 0) {
            $meal = mActivityMeal::admGetActivityMealById($mealId, true);

            if($meal['shop_id'] != $post['shop_id']) {
                throw new \Exception('抱歉，您没有权限编辑此套餐');
            }

            if($meal['status'] == mActivityMeal::STATUS_START) {
                $post['start_time'] = $meal['start_time'];
                return $meal;
            } else if ($meal['status'] == mActivityMeal::STATUS_END) {
                throw new \Exception('抱歉，已结束的套餐只能查看');
            }

        }

        return true;

    }
}